using System.Net;
using System.Text;
using Newtonsoft.Json;


namespace LuUpgrade.Controller
{
    public class NetClient
    {
        private readonly HttpClient _client = new();


        public async Task<string> SendJsonPostRequest(string url, object data)
        {
            try
            {
                var jsonContext =
                    new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
                // _client.BaseAddress = new Uri("https://api.example.com/");
                var response = await _client.PostAsync(url, jsonContext);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    throw new HttpRequestException($"post请求失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"发送post请求时出错: {ex.Message}");
            }
        }
    }


    public class NetServer
    {
        private readonly HttpListener _listener;

        public NetServer(IEnumerable<string> prefixes)
        {
            _listener = new HttpListener();
            foreach (var prefix in prefixes)
            {
                _listener.Prefixes.Add(prefix);
            }
        }


        public void Start()
        {
            _listener.Start();
            Console.WriteLine("服务器启动!!!");
            while (true)
            {
                var context = _listener.GetContext();
                if (context.Request.HttpMethod == "POST")
                {
                    HandleRequest(context);
                }
                else
                {
                    HandleUnsupportedMethod(context);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }

        private static void HandleRequest(HttpListenerContext context)
        {
            string requestContent;
            using (var inputStream = context.Request.InputStream)
            {
                using var reader = new StreamReader(inputStream, context.Request.ContentEncoding);
                requestContent = reader.ReadToEnd();
            }

            Console.WriteLine(requestContent);

            string jsonResponse;
            var res = new Dictionary<string, object?>
            {
                { "code", 200 },
                { "msg", "success" },
                { "data", "" }
            };

            if (requestContent != "\"\"" && requestContent != "{}")
            {
                res["data"] = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestContent);

                jsonResponse = JsonConvert.SerializeObject(res, Formatting.Indented);
            }
            else
            {
                Console.WriteLine("请求参数为空!");
                res["code"] = 300;
                res["msg"] = "参数为空!";
                jsonResponse = JsonConvert.SerializeObject(res, Formatting.Indented);
            }

            var buffer = Encoding.UTF8.GetBytes(jsonResponse);
            context.Response.ContentType = "application/json";
            context.Response.ContentLength64 = buffer.Length;

            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.Close();
        }


        private static void HandleUnsupportedMethod(HttpListenerContext context)
        {
            // Return a message indicating unsupported method
            const string jsonResponse = "{\"msg\": \"请求方式不支持!!\"}";

            var buffer = Encoding.UTF8.GetBytes(jsonResponse);

            context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
            context.Response.ContentType = "application/json";
            context.Response.ContentLength64 = buffer.Length;

            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.Close();
        }


        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
            Console.WriteLine("服务停止!!!!");
        }
    }
}